import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet(name = "downloadServlet", value = "/downloadServlet")
public class downloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决中文乱码问题
        response.setCharacterEncoding("utf-8");
        //解决响应中文乱码问题
        response.setContentType("text/html;charset=utf-8");
        //获取用户传递过来的参数(根据传递过来的键获取对应的值)
        //获取 = 文件名(1.jpg之类的)
        String filename = request.getParameter("filename");

        //获取ServletContext对象
        ServletContext servletContext = getServletContext();
        //获取文件路径                                      注意 : 应该是前面的路径 拼接后面的文件名
        String realPath = servletContext.getRealPath("/WEB-INF/download/"+filename);
        System.out.println(realPath);
        //获取文件类型
        String filename1 = servletContext.getMimeType(filename);

        //获取文件在磁盘中的文件
        File f = new File(realPath);
        //判断文件知否存在
        if (f.exists()) {
            //设置浏览器以附件形式下载
            response.setHeader("Content-Disposition","attachment;filename="+filename);
            //正确表示存在
            //告诉浏览器文件类型
            response.setContentType(filename1);
            //创建本地输入流和网络输出流
            FileInputStream fileInputStream = new FileInputStream(realPath);
            ServletOutputStream outputStream = response.getOutputStream();

            //读取并输出文件
            byte[] b = new byte[1024];
            int x;
            if ((x = fileInputStream.read(b)) != -1) {
                outputStream.write(b, 0, x);
            }
            fileInputStream.close();
            outputStream.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
